package com.penghaisoft.microwms.product.service.impl;

import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.data.model.ProScrapOut;
import com.penghaisoft.microwms.common.data.model.ProScrapOutSn;
import com.penghaisoft.microwms.common.data.model.ProSellOut;
import com.penghaisoft.microwms.common.data.model.ProSellOutSn;
import com.penghaisoft.microwms.common.dto.ProScrapOutDto;
import com.penghaisoft.microwms.common.dto.ProSellOutDto;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.dto.TransResult;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.common.service.BaseService;
import com.penghaisoft.microwms.common.wms.model.ProStorageSn;
import com.penghaisoft.microwms.product.dao.ProSellOutMapper;
import com.penghaisoft.microwms.product.dao.ProSellOutSnMapper;
import com.penghaisoft.microwms.product.dao.ProStorageSnMapper;
import com.penghaisoft.microwms.product.service.IProSellOutService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

/**
 * <p>
 * 业务逻辑实现类
 * </p>
 * 
 * @author
 * @createDate 
 **/
@Service
public class ProSellOutServiceImpl extends BaseService implements IProSellOutService{

	@Autowired
	private ProSellOutMapper proSellOutMapper;

	@Autowired
	private ProSellOutSnMapper proSellOutSnMapper;

	@Autowired
	private ProStorageSnMapper proStorageSnMapper;

  /**
   * 新增记录
   * @param proSellOut
   * @return
   */
	@Override
	public Resp create(ProSellOut proSellOut){
		proSellOutMapper.create(proSellOut);
		return success();
	}

  /**
   * 删除记录（逻辑删除）
   * @param proSellOut
   * @return
   */
	@Override
	public Resp delete(ProSellOut proSellOut){
		proSellOutMapper.delete(proSellOut);
		return success();
	}

  /**
   * 查询列表
   * @param page,rows
   * @param condition
   * @return
   */
	@Override
	public Pager<ProSellOut> findListByCondition(int page, int rows, ProSellOut condition){
		Pager<ProSellOut> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);
		condition.preQuery();
		long size = proSellOutMapper.queryCount(condition);
		List<ProSellOut> records = new ArrayList<>();
		if(size > 0){
			records = proSellOutMapper.queryList(pager,condition);
		}
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}

  /**
   * 查询单条
   * @param id
   * @return
   */
	@Override
	public ProSellOut findById(String id){
		return proSellOutMapper.queryById(id);
	}

  /**
   * 修改记录
   * @param proSellOut
   * @return
   */
	@Override
	public Resp update(ProSellOut proSellOut){
		proSellOutMapper.updateBySelect(proSellOut);
		return success();
	}
	
	/* @Title: updateNew 
	 * @Description: 更新数量【增加数量判断】
	 * @author luoteng
	 * @date 2018年8月21日 上午11:25:02 
	 */
	@Override
	@Transactional
	public Resp updateNew(ProSellOut proSellOut){
		int updateNum = proSellOutMapper.updateBySelectNew(proSellOut);
		if(updateNum < 1){
			throw new RuntimeException("销售出库单中该型号的需求数量不能修改小于当前实发数量！");
		}
		return success();
	}

	/**
	 *@wzhg 18614 成品销售出库单创建
	 * @param list
	 * @param sellOutNo
	 * @param loginName
     * @return
     */
	@Override
	public Resp insert(List<ProSellOut> list, String sellOutNo, String loginName) {
		Date now = new Date();
		HashSet<String> allSet = new HashSet<String>();
		for(int i = 0 ; i < list.size(); i ++){
			ProSellOut sellOut = list.get(i);

			StringBuffer uniqueStr = new StringBuffer("");
			uniqueStr.append(sellOut.getModel());
			uniqueStr.append(sellOut.getModelType());
			if(allSet.contains(uniqueStr.toString())){
				Resp resp = new Resp();
				resp.setCode(Constant.FAIL);
				resp.setMsg("选择的型号、型号类型重复");
				return resp;
			}else{
				allSet.add(uniqueStr.toString());
			}
		}
		for(int i = 0 ; i < list.size(); i ++){
			ProSellOut sellOut = list.get(i);

//    		合同编号、型号、型号类型、需求数量 页面传递的参数已经提供
			sellOut.setSellOutNo(sellOutNo);
			sellOut.setActiveFlag("1");
			sellOut.setGmtCreate(now);
			sellOut.setCreateBy(loginName);
//			0新建 1出库中 2出库完成
			sellOut.setSellOutStatus("0");
 			sellOut.setRealAmount(new BigDecimal(0));

			proSellOutMapper.create(sellOut);
		}

		return success();
	}

	@Override
	public Resp loadBill(ProSellOut proSellOut) {
		Resp resp = new Resp();

		proSellOut.setActiveFlag("1");
		List<ProSellOut> list = proSellOutMapper.queryByAny(proSellOut);

		if(list == null || list.isEmpty()){
			resp.setCode(Constant.FAIL);
			resp.setMsg("该销售出库单号不存在");
		}else{
			Boolean flag_all_2 = true;
			for(ProSellOut tmp : list){
//				0新建 1出库中 2出库完成
				if(!"2".equals(tmp.getSellOutStatus())){
					flag_all_2 = false;
				}
				
//				0新建 1出库中 2出库完成 3审核通过 4审核不通过
				if("0".equals(tmp.getSellOutStatus())){
					resp.setCode(Constant.FAIL);
					resp.setMsg("该销售出库单未审核！");
					return resp;
				}else if("4".equals(tmp.getSellOutStatus())){
					resp.setCode(Constant.FAIL);
					resp.setMsg("该销售出库单审核不通过！");
					return resp;
				}
			}

			if(flag_all_2){
				resp.setCode(Constant.FAIL);
				resp.setMsg("该销售出库单已经发货完成！");
				return resp;
			}

			resp.setCode(Constant.SUCCESS);
			resp.setMsg("提单成功");
		}

		return resp;
	}

	/**
	 * @Title queryListByAny
	 * @Description 根据出库单号查询数据
	 * @copy luoteng @edit wzhg
	 * @date 2018年6月13日:下午4:49:07
	 * @param condition
	 * @return
	 */
	@Override
	public List<ProSellOut> queryListByAny(ProSellOut condition){
		return  proSellOutMapper.queryByAny(condition);
	}

	/**
	 * @Title handInScanBarcode
	 * @Description 出库扫码
	 * @copy luoteng @edit wzhg
	 * @date 2018年6月14日:下午2:01:42
	 * @param proSellOutDto
	 * @return
	 */
	@Transactional
	@Override
	public TransResult sellOutScanBarcode(ProSellOutDto proSellOutDto){
		TransResult result = new TransResult();
		result.setCode(Constant.SUCCESS);

		Date now = new Date();

		ProStorageSn proStorageSn = new ProStorageSn();
		proStorageSn.setBarcode(proSellOutDto.getBarcode());
		proStorageSn.setActiveFlag("1");

		List<ProStorageSn> storageList = proStorageSnMapper.queryByAny(proStorageSn);
		if(storageList == null || storageList.isEmpty()){
			result.setCode(Constant.FAIL);
			result.setMsg("该成品条码不存在。");
			return result;
		}else if(storageList.size() > 1){
			result.setCode(Constant.FAIL);
			result.setMsg("该成品条码重复。");
			return result;
		}else{
			ProStorageSn storageSnTmp = storageList.get(0);

//        	0：可用 1：冻结 2：已出库 3：抽检冻结
			if(storageSnTmp.getBarcodeStatus() == null){
				result.setCode(Constant.FAIL);
				result.setMsg("该条码状态为空。");
				return result;
			}else if(storageSnTmp.getBarcodeStatus().equals("2")){
				result.setCode(Constant.FAIL);
				result.setMsg("该条码已出库。");
				return result;
			}else if(storageSnTmp.getBarcodeStatus().equals("1") || storageSnTmp.getBarcodeStatus().equals("3")){
				result.setCode(Constant.FAIL);
				result.setMsg("该条码已冻结。");
				return result;
			}else if(storageSnTmp.getBarcodeStatus().equals("0")){

				ProSellOutSn proSellOutSn = new ProSellOutSn();
				proSellOutSn.setBarcode(proSellOutDto.getBarcode());
				proSellOutSn.setActiveFlag("1");

				List<ProSellOutSn> sellOutSnList = proSellOutSnMapper.queryByAny(proSellOutSn);
				if(sellOutSnList != null && !sellOutSnList.isEmpty()){
					result.setCode(Constant.FAIL);
					result.setMsg("该条码已经扫描，不能再次扫描!");
					return result;
				}else{
					ProSellOut proSellOut = new ProSellOut();
					proSellOut.setSellOutNo(proSellOutDto.getSellOutNo());
					proSellOut.setContractNo(proSellOutDto.getContractNo());
					proSellOut.setModel(storageSnTmp.getModel());
					proSellOut.setModelType(storageSnTmp.getModelType());
					proSellOut.setActiveFlag("1");

					List<ProSellOut> sellOutList = proSellOutMapper.queryByAny(proSellOut);
					if (sellOutList == null || sellOutList.isEmpty()) {
						result.setCode(Constant.FAIL);
						result.setMsg("该条码不是出库单所需型号!");
						return result;
					}else{
						ProSellOut sellOutTmp = sellOutList.get(0);
						if(!sellOutTmp.getContractNo().equals(storageSnTmp.getContractNo())){
							result.setCode(Constant.FAIL);
							result.setMsg("该条码合同号（" + storageSnTmp.getContractNo() + "）与该手工出库单的合同号（" + sellOutTmp.getContractNo() + "）不相同!");
							return result;
						}
//						List<ProHandIn> rtnList = new ArrayList<ProHandIn>();
						List<ProSellOut> rtnList = new ArrayList<>();

						// 需求数量
						BigDecimal requireAmount = sellOutTmp.getRequireAmount() ==null ? BigDecimal.ZERO : sellOutTmp.getRequireAmount();
						// 已发数量
						BigDecimal realAmount = sellOutTmp.getRealAmount() == null ? BigDecimal.ZERO : sellOutTmp.getRealAmount();

//    					C-STG-L:塑套钢-螺旋钢管 C-STG-W:塑套钢-无缝钢管 C-GTG-L:钢套钢-螺旋钢管 C-GTG-W:钢套钢-无缝钢管 C-BLG-L:玻璃钢-螺旋钢管 C-BLG-W:玻璃钢-无缝钢管 C-W:弯头 C-ST:三通 C-BJ:变径 C-G:固定支架
						String modelType = sellOutTmp.getModelType() == null ? "" : sellOutTmp.getModelType();

						if (realAmount.compareTo(requireAmount) == 0
								|| requireAmount.compareTo(realAmount) < 0) {
							result.setCode(Constant.FAIL);
							result.setMsg("该型号已经扫码完成，无需继续扫码!");
							return result;
						} else {
//							0新建 1出库中 2出库完成
							sellOutTmp.setSellOutStatus("1");
							sellOutTmp.setLastModifiedBy(proSellOutDto.getLoginName());
							sellOutTmp.setGmtModified(now);
//							更新数量的sql 去掉realAmout的更新
							sellOutTmp.setRealAmount(null);

							if(modelType.equals(Constant.PRO_MODEL_TYPE_WT) || modelType.equals(Constant.PRO_MODEL_TYPE_ST)
									|| modelType.equals(Constant.PRO_MODEL_TYPE_BJ) || modelType.equals(Constant.PRO_MODEL_TYPE_G)){
								sellOutTmp.setRealAmountAdd(new BigDecimal(1));
								realAmount = realAmount.add(new BigDecimal(1));
							}else{
								sellOutTmp.setRealAmountAdd(storageSnTmp.getAmount());
								realAmount = realAmount.add(storageSnTmp.getAmount());
							}
						}

						Integer rtVal = proSellOutMapper.updateBySelect(sellOutTmp);
						if(rtVal != 1){
							throw new RuntimeException("扫描条码失败，更新条数存在问题!");
						}

//						该实发数量只是提供给手持显示，后台sql加数量
						sellOutTmp.setRealAmount(realAmount);
//						返回给手持数据
						rtnList.add(sellOutTmp);
						result.setList(rtnList);

/*						ProHandIn yzOb = new ProHandIn();
						yzOb.setHandInId(handInTmp.getHandInId());
						List<ProHandIn> yzList = proHandInMapper.queryByAny(yzOb);*/

						ProSellOut yzOb = new ProSellOut();
						yzOb.setSellOutId(sellOutTmp.getSellOutId());
						List<ProSellOut> yzList = proSellOutMapper.queryByAny(yzOb);

/*						BigDecimal maxRealAmout = requireAmount.add(Constant.PRO_STATIC_METER);
						if(modelType.equals(Constant.PRO_MODEL_TYPE_WT) || modelType.equals(Constant.PRO_MODEL_TYPE_ST)
								|| modelType.equals(Constant.PRO_MODEL_TYPE_BJ) || modelType.equals(Constant.PRO_MODEL_TYPE_G)){
							if(yzList.get(0).getRequireAmount().compareTo(yzList.get(0).getRealAmount()) < 0 ){
								throw new RuntimeException("该型号已经扫码完成，无需继续扫码!");
							}
						}else{
							if(maxRealAmout.compareTo(yzList.get(0).getRealAmount()) < 0){
								throw new RuntimeException("该型号已经扫码完成，无需继续扫码!");
							}
						}*/

						ProSellOutSn sellOutSnInsertOb = new ProSellOutSn();
						sellOutSnInsertOb.setSellOutNo(sellOutTmp.getSellOutNo());
						sellOutSnInsertOb.setContractNo(sellOutTmp.getContractNo());
						sellOutSnInsertOb.setBarcode(proSellOutDto.getBarcode());
						sellOutSnInsertOb.setModel(sellOutTmp.getModel());
						sellOutSnInsertOb.setModelDesc(sellOutTmp.getModelDesc());
						sellOutSnInsertOb.setModelType(sellOutTmp.getModelType());
						sellOutSnInsertOb.setType(sellOutTmp.getType());
						sellOutSnInsertOb.setAmount(storageSnTmp.getAmount());
						sellOutSnInsertOb.setUnit(storageSnTmp.getUnit());
						sellOutSnInsertOb.setWlCode(storageSnTmp.getWlCode());
						sellOutSnInsertOb.setActiveFlag("1");
						sellOutSnInsertOb.setGmtCreate(now);
						sellOutSnInsertOb.setCreateBy(proSellOutDto.getLoginName());

						proSellOutSnMapper.create(sellOutSnInsertOb);

//						List<ProHandInSn> handInSnYzList = proHandInSnMapper.queryByAny(proHandInSn);
//						if(handInSnYzList.size() > 1){
//							throw new RuntimeException();
//						}

//						0：可用 1：冻结 2：已出库 3：抽检冻结
						storageSnTmp.setBarcodeStatus("2");
						storageSnTmp.setLastModifiedBy(proSellOutDto.getLoginName());
						storageSnTmp.setGmtModified(now);

						Integer rtVal1 = proStorageSnMapper.updateByBarcodeStatus0(storageSnTmp);
						if(rtVal1 != 1){
							throw new RuntimeException("当前条码已经出库，或者被冻结！");
						}
					}
				}

			}
		}

		return result;
	}

	/**
	 * @Title handInComplete
	 * @Description 确认完成
	 * @copy luoteng @edit wzhg
	 * @date 2018年6月15日:下午3:03:22
	 * @param proSellOutDto
	 * @return
	 */
	@Transactional
	@Override
	public TransResult sellOutComplete(ProSellOutDto proSellOutDto){
		TransResult result = new TransResult();
		result.setCode(Constant.SUCCESS);

		Date now = new Date();

		ProSellOut proSellOut = new ProSellOut();
		proSellOut.setActiveFlag("1");
		proSellOut.setSellOutNo(proSellOutDto.getSellOutNo());

		List<ProSellOut> sellOutList = proSellOutMapper.queryByAny(proSellOut);
		if(sellOutList == null || sellOutList.isEmpty()){
			result.setCode(Constant.FAIL);
			result.setMsg("该手工出库单不存在!");
			return result;
		}else{
			for(ProSellOut tmp : sellOutList){
				// 需求数量
				BigDecimal requireAmount = tmp.getRequireAmount() ==null ? BigDecimal.ZERO : tmp.getRequireAmount();
				// 已发数量
				BigDecimal realAmount = tmp.getRealAmount() == null ? BigDecimal.ZERO : tmp.getRealAmount();

				BigDecimal maxRealAmout = Constant.PRO_STATIC_METER.add(requireAmount);

				if(requireAmount.compareTo(realAmount) > 0){
					result.setCode(Constant.FAIL);
					result.setMsg("该出库单未扫码完毕!");
					return result;
				}else if(maxRealAmout.compareTo(realAmount) < 0){
					result.setCode(Constant.FAIL);
					result.setMsg("该出库单扫码数量超过需求数量!");
					return result;
				}
			}

			ProSellOutSn snTmp = new ProSellOutSn();
			snTmp.setSellOutNo(proSellOutDto.getSellOutNo());
//			 查询手工入库单 开始、结束扫描时间
			ProSellOutSn sn = proSellOutSnMapper.selectBeginEndScanTime(snTmp);



			ProSellOut upOb = new ProSellOut();
			upOb.setSellOutNo(proSellOutDto.getSellOutNo());
			upOb.setScanTimeBegin(sn.getScanTimeBegin());
			upOb.setScanTimeEnd(sn.getScanTimeEnd());
//			0新建 1入库中 2入库完成
			upOb.setSellOutStatus("2");
			upOb.setLastModifiedBy(proSellOutDto.getLoginName());
			upOb.setGmtModified(now);

			proSellOutMapper.updateBySellOutNo(upOb);
		}

		return result;
	}

	/**
	 * @Title scrapOutDelBarcode
	 * @Description 删除条码
	 * @copy luoteng @edit wzhg
	 * @date 2018年6月14日:下午5:25:02
	 * @param proSellOutDto
	 * @return
	 */
	@Transactional
	@Override
	public TransResult sellOutDelBarcode(ProSellOutDto proSellOutDto){
		TransResult result = new TransResult();
		result.setCode(Constant.SUCCESS);

		Date now = new Date();

		ProStorageSn proStorageSn = new ProStorageSn();
		proStorageSn.setBarcode(proSellOutDto.getBarcode());
//    	0：可用 1：冻结 2：已出库 3：抽检冻结
		proStorageSn.setBarcodeStatus("2");
		proStorageSn.setActiveFlag("1");

		List<ProStorageSn> storageList = proStorageSnMapper.queryByAny(proStorageSn);
		if(storageList == null || storageList.isEmpty()){
			result.setCode(Constant.FAIL);
			result.setMsg("该成品条码不存在或未出库。");
			return result;
		}else if(storageList.size() > 1){
			result.setCode(Constant.FAIL);
			result.setMsg("该成品条码重复。");
			return result;
		}else{
			ProStorageSn storageSnTmp = storageList.get(0);

			ProSellOutSn proSellOutSn = new ProSellOutSn();
			proSellOutSn.setSellOutNo(proSellOutDto.getSellOutNo());
			proSellOutSn.setBarcode(proSellOutSn.getBarcode());
			proSellOutSn.setActiveFlag("1");

			List<ProSellOutSn> sellOutSnList = proSellOutSnMapper.queryByAny(proSellOutSn);

			if(sellOutSnList == null || sellOutSnList.isEmpty()){
				result.setCode(Constant.FAIL);
				result.setMsg("该条码未扫描!");
				return result;
			}else{
				ProSellOutSn proSellOutSnTmp = sellOutSnList.get(0);

				ProSellOut proSellOut = new ProSellOut();
				proSellOut.setSellOutNo(proSellOutDto.getSellOutNo());
				proSellOut.setContractNo(storageSnTmp.getContractNo());
				proSellOut.setModel(storageSnTmp.getModel());
				proSellOut.setModelType(storageSnTmp.getModelType());
				proSellOut.setActiveFlag("1");

				List<ProSellOut> sellOutList = proSellOutMapper.queryByAny(proSellOut);
				if (sellOutList == null || sellOutList.isEmpty()) {
					result.setCode(Constant.FAIL);
					result.setMsg("条码型号与出库单所需型号不一致!");
					return result;
				}else{
					ProSellOut sellOutTmp = sellOutList.get(0);
					List<ProSellOut> rtnList = new ArrayList<>();

					// 需求数量
					BigDecimal requireAmount = sellOutTmp.getRequireAmount() ==null ? BigDecimal.ZERO : sellOutTmp.getRequireAmount();
					// 已发数量
					BigDecimal realAmount = sellOutTmp.getRealAmount() == null ? BigDecimal.ZERO : sellOutTmp.getRealAmount();

//					C-STG-L:塑套钢-螺旋钢管 C-STG-W:塑套钢-无缝钢管 C-GTG-L:钢套钢-螺旋钢管 C-GTG-W:钢套钢-无缝钢管 C-BLG-L:玻璃钢-螺旋钢管 C-BLG-W:玻璃钢-无缝钢管 C-W:弯头 C-ST:三通 C-BJ:变径 C-G:固定支架
					String modelType = sellOutTmp.getModelType() == null ? "" : sellOutTmp.getModelType();

//					0新建 1入库中 2入库完成
					sellOutTmp.setSellOutStatus("1");
					sellOutTmp.setLastModifiedBy(proSellOutDto.getLoginName());
					sellOutTmp.setGmtModified(now);

					if(modelType.equals(Constant.PRO_MODEL_TYPE_WT) || modelType.equals(Constant.PRO_MODEL_TYPE_ST)
							|| modelType.equals(Constant.PRO_MODEL_TYPE_BJ) || modelType.equals(Constant.PRO_MODEL_TYPE_G)){
						sellOutTmp.setRealAmountDel(new BigDecimal(1));
						realAmount = realAmount.subtract(new BigDecimal(1));
					}else{
						sellOutTmp.setRealAmountDel(storageSnTmp.getAmount());
						realAmount = realAmount.subtract(storageSnTmp.getAmount());
					}

//					Integer rtVal = proScrapOutMapper.updateBySelect(scrapOutTmp);
					Integer rtVal = proSellOutMapper.updateBySelect(sellOutTmp);
					if(rtVal != 1){
						throw new RuntimeException("删除条码失败，更新条数存在问题!");
					}

//					该实发数量只是提供给手持显示，后台sql加数量
					sellOutTmp.setRealAmount(realAmount);
//					返回给手持数据
					rtnList.add(sellOutTmp);
					result.setList(rtnList);

					proSellOutSnTmp.setActiveFlag("0");
					proSellOutSnTmp.setLastModifiedBy(proSellOutDto.getLoginName());
					proSellOutSnTmp.setGmtModified(now);

					Integer rtVal1 = proSellOutSnMapper.updateBySelect(proSellOutSnTmp);
					if(rtVal1 != 1){
						throw new RuntimeException("删除条码失败，更新条数存在问题!");
					}

//					0：可用 1：冻结 2：已出库 3：抽检冻结
					storageSnTmp.setBarcodeStatus("0");
					storageSnTmp.setLastModifiedBy(proSellOutDto.getLoginName());
					storageSnTmp.setGmtModified(now);

					Integer rtVal2 = proStorageSnMapper.updateByBarcodeStatus2(storageSnTmp);
					if(rtVal2 != 1){
						throw new RuntimeException("删除条码失败，更新条数存在问题!");
					}
				}
			}
		}

		return result;
	}


}
